package net.ib.mtalk.ui.widget;

import net.ib.mtalk.util.Dip;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Gallery;

/**
 * 갤러리를 드래그할 때 연속으로 여러 장이 넘어가지 않게 잡아주는 갤러리.
 * 한 번 드래그에 한 장씩만 넘어간다.
 * 
 * @author Arngard
 *
 */
public class FlingStopGallery extends Gallery {

	public FlingStopGallery(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public FlingStopGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public FlingStopGallery(Context context) {
		super(context);
		init(context);
	}
	
	float limit = Dip.toPixel(320f*1.3f);
	private void init(Context context) {
		Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		int width = display.getWidth();
		limit = (float) (width * 1.3); // Velocity Factor.
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		/*/
		float velX = 0;
		float limit = Dip.toPixel(320f*1.3f);
		if (isLeftFling(e1, e2, velocityX)) {
			velX = Math.min(velocityX, limit);
		} else {
			velX = Math.max(velocityX, -limit);
		}
		if (getSelectedItemPosition() == 1 || getSelectedItemPosition() == getAdapter().getCount() - 2) {
			velX = velX > 0 ? 1 : -1;
		}
		MTalkLogWriter.w("velocityX: "+velocityX+", velX: "+velX);
		return super.onFling(e1, e2, velX, velocityY);
		//*/
		/*/
		int kEvent;
		if (isLeftFling(e1, e2, velocityX)) {
			kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		}
		else{ //Otherwise scrolling right
			kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		}
		onKeyDown(kEvent, null);
		return true;
		//*/
		//*/
		int position = getSelectedItemPosition();
		if (isLeftFling(e1, e2, velocityX)) {
			if (position-1 >= 0)
				setSelection(position-1, true);
		} else {
			if (position+1 <= getCount()-1)
				setSelection(position+1, true);
		}
		return true;
		//*/
	}

	private boolean isLeftFling(MotionEvent e1, MotionEvent e2, float velocityX) {
		try {
			return e2.getRawX() > e1.getRawX(); 
		} catch (Exception e) {
			return velocityX > 0;
		}
	}

}
